﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xaml.Behaviors;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace YF_Music.Core.Behavior
{
  public class SliderDragBehavior : Behavior<Slider>
  {
    public static readonly DependencyProperty DragCompletedCommandProperty =
        DependencyProperty.Register(nameof(DragCompletedCommand), typeof(ICommand), typeof(SliderDragBehavior), new PropertyMetadata(null));

    public ICommand DragCompletedCommand
    {
      get => (ICommand)GetValue(DragCompletedCommandProperty);
      set => SetValue(DragCompletedCommandProperty, value);
    }

    public static readonly DependencyProperty IsDraggingProperty =
        DependencyProperty.Register(nameof(IsDragging), typeof(bool), typeof(SliderDragBehavior), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public bool IsDragging
    {
      get => (bool)GetValue(IsDraggingProperty);
      set => SetValue(IsDraggingProperty, value);
    }

    protected override void OnAttached()
    {
      base.OnAttached();
      AssociatedObject.AddHandler(Thumb.DragStartedEvent, new DragStartedEventHandler(OnDragStarted));
      AssociatedObject.AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler(OnDragCompleted));

    }

    protected override void OnDetaching()
    {
      base.OnDetaching();
      AssociatedObject.RemoveHandler(Thumb.DragStartedEvent, new DragStartedEventHandler(OnDragStarted));
      AssociatedObject.RemoveHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler(OnDragCompleted));
    }

    private void OnDragStarted(object sender, DragStartedEventArgs e)
    {
      IsDragging = true;
    }

    private void OnDragCompleted(object sender, DragCompletedEventArgs e)
    {
      IsDragging = false;
      if (DragCompletedCommand != null && DragCompletedCommand.CanExecute(AssociatedObject.Value))
      {
        DragCompletedCommand.Execute(AssociatedObject.Value);
      }
    }

  }
}
